<template>
  <el-header class="header">
    <div class="header-left">
      <el-icon class="toggle-sidebar" @click="toggleSidebar">
        <Menu />
      </el-icon>
      <router-link to="/" class="logo">
        <img src="/logo.svg" alt="Logo" class="logo-icon">
        <span class="site-title">{{ siteTitle }}</span>
      </router-link>
    </div>

    <div class="header-center">
      <el-input v-model="searchQuery" placeholder="搜索" class="search-input" @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon class="search-icon">
            <Search />
          </el-icon>
        </template>
        <template #suffix>
          <el-icon class="mic-icon">
            <Microphone />
          </el-icon>
        </template>
      </el-input>
    </div>

    <div class="header-right">
      <template v-if="!isAuthenticated">
        <el-button class="sign-in-button" @click="$router.push('/login')">
          <!-- 移除图标 -->
          <!-- <el-icon><Avatar /></el-icon> -->
          登录
        </el-button>
        <!-- 添加注册按钮 -->
        <el-button class="register-button" @click="$router.push('/register')">
          注册
        </el-button>
      </template>

      <template v-else>
        <el-dropdown trigger="hover" @command="handleCreateCommand">
          <el-button type="primary" class="create-button">
            <el-icon>
              <Plus />
            </el-icon>
            <el-icon>
              <CaretBottom />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="upload">
                <el-icon>
                  <VideoCamera />
                </el-icon>上传视频
              </el-dropdown-item>
              <el-dropdown-item command="post">
                <el-icon>
                  <Document />
                </el-icon>发帖
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-icon class="notification-icon">
          <Bell />
        </el-icon>

        <el-dropdown trigger="click" @command="handleCommand">
          <div class="user-avatar">
            <el-avatar :size="40" :src="currentUser?.avatar">
              <el-icon>
                <User />
              </el-icon>
            </el-avatar>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon>
                  <Avatar />
                </el-icon>个人资料
              </el-dropdown-item>
              <el-dropdown-item command="my-videos">
                <el-icon>
                  <VideoCamera />
                </el-icon>我的视频
              </el-dropdown-item>
              <!-- 添加 我的帖子 -->
              <el-dropdown-item command="my-posts">
                <el-icon>
                  <Document />
                </el-icon>我的帖子
              </el-dropdown-item>

              <el-dropdown-item command="subscriptions">
                <el-icon>
                  <StarFilled />
                </el-icon>我的订阅 <!-- 修改文本和图标，与侧边栏一致 -->
              </el-dropdown-item>
              <!-- 添加 账号设置 -->
              <el-dropdown-item command="settings">
                <el-icon>
                  <Setting />
                </el-icon>账号设置
              </el-dropdown-item>
              <el-dropdown-item v-if="isAdmin" command="admin" divided>
                <el-icon>
                  <Setting />
                </el-icon>后台管理
              </el-dropdown-item>

              <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </div>
  </el-header>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import {
  Menu,
  Search,
  Microphone,
  Avatar,
  Plus,
  CaretBottom,
  VideoCamera,
  Document,
  Bell,
  Star,
  StarFilled,
  VideoPlay,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'

// 定义后端服务器地址 (从环境变量读取)
const backendUrl = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3000'; // 提供一个默认值

const store = useStore()
const router = useRouter()

// 恢复搜索相关
const searchQuery = ref('')
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    router.push(`/search?q=${encodeURIComponent(searchQuery.value.trim())}`)
  }
}

// 用户状态
const isAuthenticated = computed(() => store.getters['auth/isAuthenticated'])
const isAdmin = computed(() => store.getters['auth/isAdmin'])
const currentUser = computed(() => store.state.auth.user)

// 网站标题
const siteTitle = computed(() => {
  return store.state.settings?.siteName || 'MedioTube' // 改回 MedioTube
})

// 侧边栏状态
const toggleSidebar = () => {
  // 切换侧边栏组件的折叠状态
  const sidebarComponent = document.querySelector('.sidebar')?.parentNode?.__vueParentComponent?.ctx
  if (sidebarComponent && sidebarComponent.isCollapse !== undefined) {
    sidebarComponent.isCollapse.value = !sidebarComponent.isCollapse.value
  }
}

// 下拉菜单操作
// 处理下拉菜单命令
const handleCommand = async (command) => {
  console.log('处理菜单命令:', command)
  console.log('当前用户角色:', store.getters['auth/isAdmin'] ? 'admin' : 'user')

  switch (command) {
    case 'profile':
      router.push('/profile') // 个人资料
      break
    case 'my-videos':
      router.push('/user/videos') // 我的视频
      break
    case 'my-posts':
      router.push('/user/posts')
      break

    case 'subscriptions':
      router.push('/user/subscriptions') // 我的订阅
      break

    case 'settings':
      router.push('/user/settings');
      break;
    case 'logout':
      handleLogout(); // 调用单独的退出登录函数
      break;
    case 'admin':
      console.log('尝试跳转到后台管理')
      await router.push('/admin')
      console.log('后台管理路由跳转完成')
      break

  }
}

// 单独的退出登录函数
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await store.dispatch('auth/logout')
    router.push('/login')
  } catch { }
}

const handleCreateCommand = (command) => {
  switch (command) {
    case 'upload':
      router.push('/upload')
      break
    case 'post':
      router.push('/post')
      break
  }
}
</script>

<style scoped>
.header {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-shrink: 0;
}

/* 恢复侧边栏切换按钮样式 */
.toggle-sidebar {
  font-size: 24px;
  cursor: pointer;
  color: #030303;
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.toggle-sidebar:hover {
  background-color: #f2f2f2;
}

/* 恢复 Logo 和标题样式 */
.logo {
  display: flex;
  align-items: center;
  gap: 4px;
  text-decoration: none;
}

.logo-icon {
  height: 20px;
}

.site-title {
  color: #0f0f0f;
  font-size: 20px;
  font-weight: normal;
  font-family: "YouTube Sans", Roboto, Arial, sans-serif;
}

/* 恢复 header-center 样式 */
.header-center {
  flex-grow: 1;
  display: flex;
  justify-content: center;
  max-width: 640px;
}

/* 恢复 search-input 样式 */
.search-input {
  width: 100%;
  max-width: 536px;
}

/* 恢复 search-input 相关深度样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 40px;
  padding-left: 16px;
  height: 40px;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}

.search-input :deep(.el-input__wrapper:focus-within) {
  border-color: #1c62b9;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.3);
}

.search-input :deep(.el-input__prefix) {
  margin-right: 8px;
}

.search-input :deep(.el-input__suffix) {
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.search-input :deep(.el-input__suffix:hover) {
  background-color: #f2f2f2;
}

.search-icon,
.mic-icon {
  font-size: 20px;
  color: #606060;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  margin-right: 10px;
  /* 向左移动一点 */
}

.sign-in-button {
  /* border: 1px solid #065fd4; */
  /* 移除边框 */
  /* color: #065fd4; */
  background-color: #FF0000;
  /* 修改背景色为亮红色 */
  color: #fff;
  /* 修改文字颜色为白色 */
  border: none;
  /* 移除边框 */
  font-size: 13px;
  /* 调小字体 */
  height: 32px;
  /* 调小高度 */
  padding: 0 14px;
  /* 调整内边距 */
  display: flex;
  align-items: center;
  border-radius: 16px;
  /* 调整圆角 */
}

.sign-in-button:hover {
  /* 添加悬停效果 */
  background-color: #CC0000;
  /* 调整悬停背景色 (稍暗的红色) */
}

/* 添加注册按钮样式 */
.register-button {
  /* 保持与登录按钮一致 */
  /* border: 1px solid #065fd4; */
  /* 移除边框 */
  /* color: #065fd4; */
  background-color: #FF0000;
  /* 修改背景色为亮红色 */
  color: #fff;
  /* 修改文字颜色为白色 */
  border: none;
  /* 移除边框 */
  font-size: 13px;
  /* 调小字体 */
  height: 32px;
  /* 调小高度 */
  padding: 0 14px;
  /* 调整内边距 */
  border-radius: 16px;
  /* 调整圆角 */
}

.register-button:hover {
  /* 添加悬停效果 */
  /* background-color: #f0f6ff; */
  /* Element Plus 边框按钮的悬停背景色 */
  background-color: #CC0000;
  /* 调整悬停背景色 (稍暗的红色) */
}

.create-button {
  background-color: transparent;
  border: none;
  color: #030303;
  padding: 8px;
  height: auto;

  &:hover {
    background-color: #f2f2f2;
    color: #030303;
  }

  .el-icon {
    font-size: 24px;
  }

  .el-icon+.el-icon {
    font-size: 12px;
    margin-left: 2px;
  }
}

.notification-icon {
  font-size: 24px;
  color: #030303;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.notification-icon:hover {
  background-color: #f2f2f2;
}

.user-avatar {
  cursor: pointer;
  display: flex;
  align-items: center;
}

/* 提高下拉菜单的 z-index */
:deep(.el-dropdown__popper) {
  z-index: 1003 !important;
  /* 确保高于侧边栏 (1001) 和头部 (1002) */
}

.el-dropdown-menu {
  .el-icon {
    margin-right: 12px;
    font-size: 20px;
    vertical-align: middle;
  }
}
</style>